﻿namespace EFS.Common
{
	public static class ReflectCopy<T1, T2> 
	{
		/// <summary>
		/// Delegate to add new object
		/// </summary>
		/// <returns></returns>
		public delegate T2 Instance();

		/// Load quote values
		public static T2[] Copy(T1[] sourceArray, Instance instance)
		{
			// check
			EFS.Common.Verify.Reference(sourceArray, "sourceArray");

			// make list
			System.Collections.Generic.List<T2> destinationList = new System.Collections.Generic.List<T2>();

			// cycle all metadatas and set data to quote details
			foreach (T1 source in sourceArray)
			{
				// new T
				T2 destination = instance();

				// copy
				Copy(source, destination);

				// add
				destinationList.Add(destination);
			}

			// done
			return destinationList.ToArray();
		}

		/// <summary>
		/// Copy properties and values
		/// </summary>
		/// <param name="source"></param>
		/// <param name="destination"></param>
		public static void Copy(T1 source, T2 destination)
		{ 
			// check
			EFS.Common.Verify.Reference(source, "source");
			EFS.Common.Verify.Reference(destination, "destination");

			// types
			System.Type sourceType = typeof(T1);
			System.Type destinationType = typeof(T2);

			// get properties
			System.Reflection.PropertyInfo[] sourcePropertyInfoArray = sourceType.GetProperties();
		
			// cycle all metadatas and set data to quote details
			foreach (System.Reflection.PropertyInfo sourcePropertyInfo in sourcePropertyInfoArray)
			{
				// get and check
				System.Reflection.PropertyInfo destinationPropertyInfo = destinationType.GetProperty(sourcePropertyInfo.Name);
				if (null != destinationPropertyInfo)
				{
					// set value
					destinationPropertyInfo.SetValue(destination, sourcePropertyInfo.GetValue(source, null), null);
				}
			}
		}
	}
}